package com.fire.service.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.fire.dao.ProviderDao;
import com.fire.pojo.ImageFile;
import com.fire.pojo.Product;
import com.fire.pojo.ProviderIdentify;
import com.fire.service.ProviderService;
import com.fire.util.ConstantKeys;
import com.fire.util.MsgInfo;
import com.fire.util.base.BooleanUtil;
import com.fire.util.base.ResultBody;

@Service
public class ProviderServiceImpl implements ProviderService {

	@Autowired
	private ProviderDao providerDao;

	/**
	 * 供应商认证接口
	 */
	@Override
	public ResultBody identify(JSONObject params, Integer userId) throws Exception {
		ResultBody result = new ResultBody();
		// 企业名称
		String companyName = params.getString("companyName");
		// 住所
		String location = params.getString("location");
		// 营业资质压缩包URL
		String companyLicenseZipUrl = params.getString("companyLicenseZipUrl");
		// 法人代表姓名
		String legalPersonName = params.getString("legalPersonName");
		// 身份证账号
		String idCardNum = params.getString("idCardNum");
		// 法人身份证照片
		String idCardPhotoIds = params.getString("idCardPhotoIds");
		// 联系人姓名
		String contactsName = params.getString("contactsName");
		// 联系人职务
		String duties = params.getString("duties");
		// 联系人手机号
		String phoneNum = params.getString("phoneNum");

		if (!BooleanUtil.StringIsNa(companyName) || !BooleanUtil.StringIsNa(location)
				|| !BooleanUtil.StringIsNa(companyLicenseZipUrl) || !BooleanUtil.StringIsNa(legalPersonName)
				|| !BooleanUtil.StringIsNa(idCardNum) || !BooleanUtil.StringIsNa(idCardPhotoIds)
				|| !BooleanUtil.StringIsNa(contactsName) || !BooleanUtil.StringIsNa(duties)
				|| !BooleanUtil.StringIsNa(phoneNum)) {
			result.setCode(MsgInfo.z_paramExcerror_code);
			result.setMessage(MsgInfo.z_paramExcerror_msg);
			return result;
		}

		ProviderIdentify identify = new ProviderIdentify(userId, companyName, location, companyLicenseZipUrl,
				legalPersonName, idCardNum, idCardPhotoIds, contactsName, duties, phoneNum);

		// 发起认证申请
		providerDao.addProviderIdentify(identify);

		// 修改供应商认证状态为:认证待审批
		providerDao.updateProviderStatus(userId);

		return result;
	}

	/**
	 * 产品发布接口
	 */
	@Override
	public ResultBody pubProduct(JSONObject params, Integer userId) throws Exception {
		ResultBody result = new ResultBody();
		// 产品信息
		String productName = params.getString("productName");
		// 批准文号
		String approvalNumber = params.getString("approvalNumber");
		// 产品规格
		String productFormat = params.getString("productFormat");
		// 装箱规格
		String packageFormat = params.getString("packageFormat");
		// 有效期
		String validDate = params.getString("validDate");
		// 零售价
		String pubPrice = params.getString("pubPrice");
		// 火拼价
		String firePrice = params.getString("firePrice");
		// 发布数量
		String pubAmount = params.getString("pubAmount");
		// 发布类型
		String pubType = params.getString("pubType");
		// 宣传内容
		String advertiseContent = params.getString("advertiseContent");
		// 产品详情压缩包URL
		String productInfoZipUrl = params.getString("productInfoZipUrl");
		// 产品资质-首营资料压缩包URL
		String qualificationZipUrl = params.getString("qualificationZipUrl");
		// 产品资质-产品资料压缩包URL
		String productZipUrl = params.getString("productZipUrl");

		if (!BooleanUtil.StringIsNa(productName) || !BooleanUtil.StringIsNa(productFormat)
				|| !BooleanUtil.StringIsNa(firePrice) || !BooleanUtil.StringIsNa(approvalNumber)
				|| !BooleanUtil.StringIsNa(packageFormat) || !BooleanUtil.StringIsNa(validDate)
				|| !BooleanUtil.StringIsNa(pubPrice) || !BooleanUtil.StringIsNa(pubAmount)
				|| !BooleanUtil.StringIsNa(pubType) || !BooleanUtil.StringIsNa(advertiseContent)
				|| !BooleanUtil.StringIsNa(productInfoZipUrl) || !BooleanUtil.StringIsNa(qualificationZipUrl)
				|| !BooleanUtil.StringIsNa(productZipUrl)) {
			result.setCode(MsgInfo.z_paramExcerror_code);
			result.setMessage(MsgInfo.z_paramExcerror_msg);
			return result;
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Product product = new Product(userId, productName, approvalNumber, productFormat, packageFormat,
				sdf.parse(validDate), Double.parseDouble(pubPrice), Double.parseDouble(firePrice),
				Integer.parseInt(pubAmount), Integer.parseInt(pubType), advertiseContent, productInfoZipUrl,
				qualificationZipUrl, productZipUrl);

		// 发布产品
		providerDao.addProduct(product);

		return result;
	}

	/**
	 * 文件上传
	 */
	@Override
	public ResultBody fileUpload(MultipartFile[] files) throws Exception {
		ResultBody result = new ResultBody();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		String dateDir = df.format(new Date());// new Date()为获取当前系统时间

		List<ImageFile> resultList = new ArrayList<ImageFile>();

		for (MultipartFile file : files) {
			if (!file.isEmpty()) {
				// 通过UUID生成上传文件名
				String serviceName = UUID.randomUUID().toString().replace("-", "").toLowerCase()
						+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

				File tempFile = new File(ConstantKeys.FILE_BASE_URL + dateDir + File.separator + serviceName);
				if (!tempFile.getParentFile().exists()) {
					tempFile.getParentFile().mkdirs();
				}

				BufferedOutputStream out = null;
				try {
					// 写入文件到磁盘
					out = new BufferedOutputStream(new FileOutputStream(tempFile));
					out.write(file.getBytes());
					out.flush();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					result.setCode(MsgInfo.z_upload_error_code);
					result.setMessage(MsgInfo.z_upload_error_msg);
					return result;
				} catch (IOException e) {
					e.printStackTrace();
					result.setCode(MsgInfo.z_upload_error_code);
					result.setMessage(MsgInfo.z_upload_error_msg);
					return result;
				} finally {
					out.close();
				}
				// 将图片插入到数据库
				ImageFile imageFile = new ImageFile("/fire/" + dateDir + "/" + serviceName);
				providerDao.addImageFile(imageFile);

				resultList.add(imageFile);
			}
		}
		result.setData(resultList);
		return result;
	}

	/**
	 * 产品列表的信息接口
	 */
	@Override
	public ResultBody productList(JSONObject params, Integer userId) throws Exception {
		ResultBody result = new ResultBody();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> productList = providerDao.getProductList(userId);
		resultMap.put("productList", productList);
		resultMap.put("countTotal", productList.size());

		// 统计各种状态的数量
		resultMap.put("countInCheck", countList(productList, 0));

		resultMap.put("countCheckPass", countList(productList, 1));

		resultMap.put("countCheckNotPass", countList(productList, 2));

		result.setData(resultMap);
		return result;
	}

	// 统计list中各状态的数量
	private static Integer countList(List<Map<String, Object>> list, Integer status) {
		int count = 0;
		for (Map<String, Object> map : list) {
			if ((Integer) map.get("pubStatus") == status) {
				count++;
			}
		}
		return count;
	}

	/**
	 * 压缩包上传
	 */
	@Override
	public ResultBody zipUpload(MultipartFile file) throws Exception {
		ResultBody result = new ResultBody();

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		String dateDir = df.format(new Date());// new Date()为获取当前系统时间

		String requestUrl = "";

		if (!file.isEmpty()) {
			// 通过UUID生成上传文件名
			String serviceName = UUID.randomUUID().toString().replace("-", "").toLowerCase()
					+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

			File tempFile = new File(ConstantKeys.ZIP_BASE_URL + dateDir + File.separator + serviceName);
			if (!tempFile.getParentFile().exists()) {
				tempFile.getParentFile().mkdirs();
			}

			BufferedOutputStream out = null;
			try {
				// 写入文件到磁盘
				out = new BufferedOutputStream(new FileOutputStream(tempFile));
				out.write(file.getBytes());
				out.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				result.setCode(MsgInfo.z_upload_error_code);
				result.setMessage(MsgInfo.z_upload_error_msg);
				return result;
			} catch (IOException e) {
				e.printStackTrace();
				result.setCode(MsgInfo.z_upload_error_code);
				result.setMessage(MsgInfo.z_upload_error_msg);
				return result;
			} finally {
				out.close();
			}

			requestUrl = "/zip/" + dateDir + "/" + serviceName;
		}

		result.setData(requestUrl);
		return result;
	}

	/**
	 * 消息列表接口
	 */
	@Override
	public ResultBody notification(JSONObject params, Integer userId) throws Exception {
		ResultBody result = new ResultBody();
		// 获取消息列表
		List<Map<String, Object>> msgList = providerDao.getNotificationList(userId);

		result.setData(msgList);
		return result;
	}

	/**
	 * 设置消息为已读
	 */
	@Override
	public ResultBody setIsRead(JSONObject params, Integer userId) throws Exception {
		ResultBody result = new ResultBody();
		// 消息id
		String notificationId = params.getString("notificationId");

		if (!BooleanUtil.StringIsNa(notificationId)) {
			result.setCode(MsgInfo.z_paramExcerror_code);
			result.setMessage(MsgInfo.z_paramExcerror_msg);
			return result;
		}

		providerDao.setIsRead(notificationId);

		return result;
	}

	/**
	 * 删除消息
	 */
	@Override
	public ResultBody deleteNotification(JSONObject params, Integer userId) throws Exception {
		ResultBody result = new ResultBody();
		// 消息id
		String notificationId = params.getString("notificationId");

		if (!BooleanUtil.StringIsNa(notificationId)) {
			result.setCode(MsgInfo.z_paramExcerror_code);
			result.setMessage(MsgInfo.z_paramExcerror_msg);
			return result;
		}

		providerDao.deleteNotification(notificationId);
		return result;
	}

	/**
	 * 取消产品发布申请
	 */
	@Override
	public ResultBody cancelPublish(JSONObject params, Integer userId) throws Exception {
		ResultBody result = new ResultBody();
		// 产品id
		String productId = params.getString("productId");

		if (!BooleanUtil.StringIsNa(productId)) {
			result.setCode(MsgInfo.z_paramExcerror_code);
			result.setMessage(MsgInfo.z_paramExcerror_msg);
			return result;
		}

		Integer status = providerDao.getPubStatus(productId);

		// 如果状态为待审批，则可以删除
		if (status == 0) {
			providerDao.cancelPublish(productId);
		} else {
			result.setData(status);
			result.setCode(MsgInfo.z_status_error_code);
			result.setMessage(MsgInfo.z_status_error_msg);
		}

		return result;
	}

	/**
	 * 更新用户基本信息
	 */
	@Override
	public ResultBody updateUserInfo(JSONObject params, Integer userId) throws Exception {
		ResultBody result = new ResultBody();
		// 新用户名
		String userName = params.getString("userName");
		// 新头像id
		String photoId = params.getString("photoId");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", userName);
		map.put("photoId", photoId);
		map.put("userId", userId);

		providerDao.updateUserInfo(map);

		// 获取用户头像返回给前端
		String imageUrl = providerDao.getImageUrl(photoId);

		result.setData(imageUrl);
		return result;
	}

}
